﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web.Security;

namespace LandandSurvey
{
    public partial class FileUpload : System.Web.UI.Page
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            if (!HasPermission())
            {
                Response.Redirect("ErrorPermission.aspx?returnurl=FileUpload.aspx");
            }
        }

        public bool HasPermission()
        {
            if (Session["user.loggedin"] == null)
            {
                return false;
            }
            if (Session["user.loggedin"].ToString() == "true")
            {
                landsdbEntities container = new landsdbEntities();
                string username = Session["user.name"].ToString();
                AppUser user = (from i in container.AppUsers
                                where i.UserName == username
                                select i).ToList().FirstOrDefault();
                if (user != null)
                {
                    if (user.UploadFiles == true)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        protected void btnUpload_Click( object sender, EventArgs e )
        {
            string type = "";
            if ( rdoNJ.Checked )
            {
                type = "jn";
            }
            else if ( rdo1186.Checked )
            {
                type = "1186";
            }
            else if ( rdoOtherPlan.Checked )
            {
                type = "Other";
            }
            if ( FileUpload1.HasFile )
            {
                string filename = string.Empty;
                try
                {

                    filename = Guid.NewGuid().ToString() + "_" + FileUpload1.FileName;
                    FileUpload1.SaveAs( ConfigurationManager.AppSettings[ "DocsFolder" ] + filename );
                }
                catch ( Exception ex )
                {
                    Session[ "app.error" ] = ex.Message;
                    Response.Redirect( "Error.aspx" );
                }

                Response.Redirect( "SuccessFileUpload.aspx?id=" + filename + "&type=" + type );
            }
        }
    }
}